<template>
    <div id="chatApp">
        <div class="chat-box">
            <div class="chat-header">{{this.message}}</div>
            <div class="chat-mian" id="chat-main">
                <div v-for="(chat,index) in chatData" :key="index">
                    <!-- 客服-文本 -->
                    <div class="info-box user-info-box" v-if="SupportText(index)">
                        <div class="time" v-if="Long(index) || index == 0">{{chat.time}}</div>
                        <div class="avatar CS-avatar">
                            <img src="../../assets/img/CS.png" alt />
                        </div>
                        <div class="info text-info">
                            <span></span>
                            <div v-html="chat.msg"></div>
                        </div>
                    </div>
                    <!-- 客服-图片 -->
                    <div class="info-box user-info-box" v-if="SupportPic(index)">
                        <div class="time" v-if="Long(index) || index == 0">{{chat.time}}</div>
                        <div class="avatar CS-avatar">
                            <img src="../../assets/img/CS.png" alt />
                        </div>
                        <div class="info img-info">
                            <img data-magnify="gallery" :data-src="chat.msg" :src="chat.msg" />
                        </div>
                    </div>

                    <!-- 游客-文本 -->
                    <div class="info-box CS-info-box" v-if="VisitorText(index)">
                        <div class="time" v-if="Long(index) || index == 0">{{chat.time}}</div>
                        <div class="avatar user-avatar">
                            <img src="../../assets/img/user.png" alt />
                        </div>
                        <div class="info text-info">
                            <span></span>
                            <div v-html="chat.msg"></div>
                        </div>
                    </div>
                    <!-- 游客-图片 -->
                    <div class="info-box CS-info-box" v-if="VisitorPic(index)">
                        <div class="time" v-if="Long(index) || index == 0">{{chat.time}}</div>
                        <div class="avatar user-avatar">
                            <img src="../../assets/img/user.png" alt />
                        </div>
                        <div class="info img-info">
                            <img data-magnify="gallery" :data-src="chat.msg" :src="chat.msg" />
                        </div>
                    </div>
                </div>

                <!-- <div class="change-but"></div> -->
            </div>
            <div class="chat-edit">
                <div id="editor" ref="editorElem" @keyup.enter.native="Send"></div>
                <button class="send-button" @click="Send">发送</button>
            </div>
        </div>
    </div>
</template>


<script>
import E from 'wangeditor';
import { log } from 'util';
import markd from './Markdown.vue';
export default {
    name: 'chatApp',
    data() {
        return {
            visit: '',
            chatData: [],
            editor: null,
            editorContent: ''
        };
    },
    computed: {
        //消息时间差，超过180秒，则显示消息发送时间
        Long: function() {
            return function(index) {
                /* if (index > 0) {
                    var prveTime1 = this.chatData[index - 1].time.slice(0, 10);
                    var prveTime2 = this.chatData[index - 1].time.slice(15);
                    var prveTime = prveTime1 + ' ' + prveTime2;

                    var nowTime1 = this.chatData[index].time.slice(0, 10);
                    var nowTime2 = this.chatData[index].time.slice(15);
                    var nowTime = nowTime1 + ' ' + nowTime2;

                    var d1 = new Date(prveTime);
                    var d2 = new Date(nowTime);

                    var longTime = parseInt(d2 - d1) / 1000;

                    if (longTime > 180) {
                        return true;
                    } else {
                        return false;
                    }
                } */
            };
        },
        //判断消息类型是 客服-文本
        SupportText: function() {
            return function(index) {
                if (this.chatData[index].user == 'support' && this.chatData[index].type == 'text') {
                    return true;
                } else {
                    return false;
                }
            };
        },
        //判断消息类型是 客服-图片
        SupportPic: function() {
            return function(index) {
                if (this.chatData[index].user == 'support' && this.chatData[index].type == 'pic') {
                    return true;
                } else {
                    return false;
                }
            };
        },
        //判断消息类型是 游客-文本
        VisitorText: function() {
            return function(index) {
                if (this.chatData[index].user == 'visitor' && this.chatData[index].type == 'text') {
                    return true;
                } else {
                    return false;
                }
            };
        },
        //判断消息类型是 游客-图片
        VisitorPic: function() {
            return function(index) {
                if (this.chatData[index].user == 'visitor' && this.chatData[index].type == 'pic') {
                    return true;
                } else {
                    return false;
                }
            };
        }
    },
    props: ['message'],
    created() {
        this.visit = this.message; //父传子点击标识
    },

    //这里用watch方法来监听父组件传过来的值，来实现实时更新
    watch: {
        message(val) {
            //message即为父组件的值，val参数为值
            this.visit = val; //将父组件的值赋给visit子组件的值
            console.log(this.message);
        }
    },
    mounted() {
        /**富文本编辑器 开始 */
        this.editor = new E(this.$refs.editorElem);
        // 编辑器的事件，每次改变会获取其html内容
        this.editor.customConfig.onchange = html => {
            this.editorContent = html;
        };
        this.editor.customConfig.menus = [
            'emoticon', // 表情
            'image', // 插入图片
            'undo', // 撤销
            'redo' // 重复
        ];
        this.editor.customConfig.pasteFilterStyle = false; // 关闭粘贴内容中的样式
        this.editor.customConfig.uploadImgShowBase64 = true; // 使用 base64 保存图片

        this.editor.customConfig.customUploadImg = function(files, insert) {
            var imgSize = (files[0].size / 1024).toFixed(0); //选择的图片大小
            // console.log(imgSize);
            var imgBase64;

            if (imgSize > 500) {
                alert('图片大小超出500KB限制');
                return false;
            } else {
                var file = files[0];
                if (window.FileReader) {
                    var reader = new FileReader();
                    reader.readAsDataURL(file);
                    //监听文件读取结束后事件
                    reader.onloadend = function(e) {
                        imgBase64 = e.target.result; // 图片base64
                        var newmsg = {
                            user: 'support', //消息来源
                            time: window.GetNowTime(), //时间
                            type: 'pic', //消息类型
                            msg: imgBase64, //图片地址
                            uid: window.uid,
                            visit: window.visit() //消息发送对象
                        };

                        console.log(newmsg);
                        ws.send(JSON.stringify(newmsg)); //发送
                        GoBottom();
                    };
                }
            }

            // 上传代码返回结果之后，将图片插入到编辑器中
            // insert(imgUrl);
        };

        // 表情面板可以有多个 tab ，因此要配置成一个数组。数组每个元素代表一个 tab 的配置
        this.editor.customConfig.emotions = [
            {
                // tab 的标题
                title: 'emoji',
                // type -> 'emoji' / 'image'
                type: 'image',
                // content -> 数组
                content: [
                    { src: 'http://www.emojidaquan.com/pics/apple/grinning-face-fb1007.png' },
                    { src: 'http://www.emojidaquan.com/pics/apple/grinning-face-with-smiling-eyes-fb1005.png' },
                    { src: 'http://www.emojidaquan.com/pics/apple/face-with-tears-of-joy-fb491.png' },
                    { src: 'http://www.emojidaquan.com/pics/apple/rolling-on-the-floor-laughing-fb1992.png' },
                    { src: 'http://www.emojidaquan.com/pics/apple/smiling-face-with-open-mouth-fb2097.png' },
                    { src: 'http://www.emojidaquan.com/pics/apple/smiling-face-with-open-mouth-and-smiling-eyes-fb2095.png' },
                    { src: 'http://www.emojidaquan.com/pics/apple/smiling-face-with-open-mouth-and-cold-sweat-fb2094.png' },
                    { src: 'http://www.emojidaquan.com/pics/apple/smiling-face-with-open-mouth-and-tightly-closed-eyes-fb2096.png' },
                    { src: 'http://www.emojidaquan.com/pics/apple/winking-face-fb2381.png' },
                    { src: 'http://www.emojidaquan.com/pics/apple/smiling-face-with-smiling-eyes-fb2099.png' },
                    { src: 'http://www.emojidaquan.com/pics/apple/face-savouring-delicious-food-fb461.png' },
                    { src: 'http://www.emojidaquan.com/pics/apple/smiling-face-with-sunglasses-fb2100.png' },
                    { src: 'http://www.emojidaquan.com/pics/apple/smiling-face-with-heart-shaped-eyes-fb2092.png' },
                    { src: 'http://www.emojidaquan.com/pics/apple/face-throwing-a-kiss-fb463.png' },
                    { src: 'http://www.emojidaquan.com/pics/apple/kissing-face-fb1165.png' },
                    { src: 'http://www.emojidaquan.com/pics/apple/kissing-face-with-smiling-eyes-fb1164.png' },
                    { src: 'http://www.emojidaquan.com/pics/apple/kissing-face-with-closed-eyes-fb1163.png' },
                    { src: 'http://www.emojidaquan.com/pics/apple/white-smiling-face-fb2360.png' },
                    { src: 'http://www.emojidaquan.com/pics/apple/slightly-smiling-face-fb2084.png' },
                    { src: 'http://www.emojidaquan.com/pics/apple/hugging-face-fb1097.png' },
                    { src: 'http://www.emojidaquan.com/pics/apple/grinning-face-with-star-eyes-fb1006.png' },
                    { src: 'http://www.emojidaquan.com/pics/apple/thinking-face-fb2213.png' },
                    { src: 'http://www.emojidaquan.com/pics/apple/face-with-one-eyebrow-raised-fb483.png' },
                    { src: 'http://www.emojidaquan.com/pics/apple/neutral-face-fb1673.png' },
                    { src: 'http://www.emojidaquan.com/pics/apple/expressionless-face-fb443.png' },
                    { src: 'http://www.emojidaquan.com/pics/apple/face-without-mouth-fb493.png' },
                    { src: 'http://www.emojidaquan.com/pics/apple/face-with-rolling-eyes-fb487.png' },
                    { src: 'http://www.emojidaquan.com/pics/apple/smirking-face-fb2101.png' },
                    { src: 'http://www.emojidaquan.com/pics/apple/persevering-face-fb1785.png' },
                    { src: 'http://www.emojidaquan.com/pics/apple/disappointed-but-relieved-face-fb377.png' },
                    { src: 'http://www.emojidaquan.com/pics/apple/face-with-open-mouth-fb486.png' },
                    { src: 'http://www.emojidaquan.com/pics/apple/zipper-mouth-face-fb2611.png' },
                    { src: 'http://www.emojidaquan.com/pics/apple/hushed-face-fb1099.png' },
                    { src: 'http://www.emojidaquan.com/pics/apple/sleepy-face-fb2075.png' },
                    { src: 'http://www.emojidaquan.com/pics/apple/tired-face-fb2234.png' },
                    { src: 'http://www.emojidaquan.com/pics/apple/speak-no-evil-monkey-fb2121.png' }
                ]
            }
        ];

        this.editor.create();
        /**富文本编辑器 结束 */

        // methods里面定义的方法, 需要赋值给window
        window.chatData = this.chatData;
        window.addd = this.addd;
        window.GetNowTime = this.GetNowTime;
        window.GoBottom = this.GoBottom;
        window.visit = this.getvisit; //标识
        window.uid = this.$cookies.get('tokenuser');
    },
    methods: {
        listupdate(_uid) {
            //调用父组件方法
            this.$parent.listupdate(_uid);
        },
        addd(add) {
            if (add.info) {
                this.chatData = add.data;
                GoBottom();
            } else {
                //判断客服是否在消息用户界面
                if (this.visit == add.uid) {
                    this.chatData.push(add);
                    GoBottom();
                } else {
                    this.listupdate(add.uid);
                }
                console.log(add);
            }
        },
        getvisit() {
            console.log(this.visit);
            return this.visit;
        },
        Send() {
            console.log('页面值' + this.visit);
            var inputmsg = this.editorContent;
            if (inputmsg.length <= 0) {
                this.$message('发送消息不能为空!');
            } else {
                if (this.visit.length > 0) {
                    if (inputmsg != '<p><br></p>') {
                        var newmsg = JSON.stringify({
                            user: 'support',
                            time: this.GetNowTime(),
                            type: 'text',
                            msg: inputmsg,
                            uid: window.uid,
                            visit: this.visit
                        });
                        // this.chatData.push(JSON.parse(newmsg));
                        console.log(newmsg);
                        ws.send(newmsg); //发送
                        this.editor.txt.html(''); //清空输入框
                        this.GoBottom(); //跳到最新消息
                    }
                } else {
                    this.$message.error('请选择发送消息用户！');
                }
            }
        },
        GetNowTime() {
            //判断是否在前面加0
            function getNow(s) {
                return s < 10 ? '0' + s : s;
            }

            var myDate = new Date();

            var year = myDate.getFullYear(); //获取当前年
            var month = myDate.getMonth() + 1; //获取当前月
            var date = myDate.getDate(); //获取当前日

            var str = '星期' + '日一二三四五六'.charAt(new Date().getDay());

            var h = myDate.getHours(); //获取当前小时数(0-23)
            var m = myDate.getMinutes(); //获取当前分钟数(0-59)
            var s = myDate.getSeconds();

            var now = year + '/' + getNow(month) + '/' + getNow(date) + ' ' + str + ' ' + getNow(h) + ':' + getNow(m) + ':' + getNow(s);

            return now;
        },
        // 跳转到最新消息
        GoBottom() {
            var scrollHeight = $('#chat-main').prop('scrollHeight');
            $('#chat-main').animate({ scrollTop: scrollHeight * this.chatData.length }, 400);
        }
    }
};

$('.w-e-icon-image')
    .parent()
    .click(function() {
        var imgInput = $('.w-e-up-img-container>div:nth-child(2)>input');
        // console.log(imgInput);
        imgInputId = '#' + imgInput[0].id;
        imgInput.removeAttr('multiple'); //禁止多选图片
    });

$(document).ready(function() {
    console.log(window.chatData);
    window.GoBottom();
});
//端口
const wsPort = 9437;
//通讯地址
const hostname = '127.0.0.1';
//创建一个对象
const ws = new WebSocket(`ws://${hostname}:${wsPort}`);

//连接建立时触发
ws.onopen = () => {
    //进入客服页面提示.
    var data = JSON.stringify({
        user: 'support', //消息来源
        time: GetNowTime(), //时间
        type: 'text', //消息类型
        msg: '<p>欢迎回来管理员！</p>', //消息内容
        visit: '', //消息发送对象
        uid: window.uid, //发送者标识
        key: '', //消息来源网站
        init: 'kefu'
    });
    ws.send(data);
};

//客户端接收服务端数据时触发
ws.onmessage = msg => {
    //接收数据，然后将数据展示到界面上
    var da = JSON.parse(msg.data);

    if (da.info) {
        console.log('吖啊啊2' + da.data);
        addd(da);
    } else {
        console.log('吖啊啊' + da.type);
        if (da.type == 'text' || da.type == 'pic') {
            console.log('咦' + da.data);
            addd(da);
            GoBottom();
        }
    }
};

//通信发生错误时触发
ws.onerror = error => {
    console.log(error);
};

//连接关闭时触发
ws.onclose = () => {
    var data = JSON.stringify({
        user: 'support', //消息来源
        time: GetNowTime(), //时间
        type: 'text', //消息类型
        msg: '<p>通讯已断开...</p>' //消息内容
    });
    addd(JSON.parse(data));
    GoBottom();
    console.log('通讯已断开...');
};
</script>

<style scoped>
@import '../../assets/css/jquery.magnify.css';

#chatApp {
    height: calc(100vh - 170px);
    /* overflow-y: hidden; */
}

.chat-box {
    height: 100%;
    width: 100%;
    /* box-shadow: 0 0 20px rgba(0, 0, 0, .3); */
    background: #fff;
    position: relative;
    padding: 0;
}

.chat-header {
    height: 40px;
    line-height: 40px;
    background: #3399ff;
    color: #fff;
    text-align: center;
    font-size: 16px;
    position: relative;
}

.chat-mian {
    width: 100%;
    height: 70%;
    /* background: #ff8000; */
    position: relative;
    overflow-y: auto;
    padding-bottom: 10px;
}

.chat-mian::-webkit-scrollbar {
    /*滚动条整体样式*/
    width: 10px;
    /*高宽分别对应横竖滚动条的尺寸*/
    height: 1px;
    display: none;
}

.chat-mian::-webkit-scrollbar-thumb {
    /*滚动条里面小方块*/
    border-radius: 10px;
    box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.1);
    background: #3d9eff;
}

.chat-mian::-webkit-scrollbar-track {
    /*滚动条里面轨道*/
    box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
    background: #ededed;
}

.change-but {
    position: absolute;
    bottom: 0;
    width: 100%;
    height: 3px;
}

.chat-edit {
    height: calc(30% - 60px);
    width: 100%;
    /* background: #06bd00; */
}

#editor {
    position: relative;
    top: 0px;
    height: 100%;
}

.info-box {
    padding: 4px 15px;
    padding-bottom: 0;
    width: 100%;
    float: left;
    box-sizing: border-box;
}

.info {
    margin-bottom: 5px;
    z-index: 1;
}

.time {
    text-align: center;
    font-size: 12px;
    color: #666;
    margin-bottom: 8px;
    margin-top: 10px;
}

.avatar {
    width: 46px;
    height: 46px;
    float: left;
    border-radius: 100%;
    overflow: hidden;
    margin-right: 30px;
}

.avatar img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.text-info,
.img-info,
.video-info {
    background: rgb(230, 230, 230);
    color: #000;
    padding: 10px 15px;
    font-size: 15px;
    float: left;
    max-width: 60%;
    border-radius: 6px;
    line-height: 26px;
    position: relative;
}

.text-info p {
    margin: 0;
    word-wrap: break-word;
}

.text-info img {
    margin: 0 5px;
    width: 22px;
    height: 22px;
    position: relative;
    top: -2px;
}

.img-info {
    background: none;
    padding: 0;
    overflow: hidden;
    max-height: 160px;
}

.img-info img {
    max-width: 100%;
    max-height: 160px;
    object-fit: cover;
    cursor: pointer;
}

.info > span {
    display: block;
    position: absolute;
    width: 24px;
    height: 16px;
    background: rgb(230, 230, 230);
    left: -3px;
    top: 14.6px;
    transform: rotate(-25deg) skewX(45deg);
    z-index: -1;
    border-radius: 5px;
}

.user-info-box .avatar {
    float: right;
    margin-right: 0;
    margin-left: 30px;
}

.user-info-box .info {
    float: right;
}

.user-info-box .info span {
    left: auto;
    right: -3px;
}

.chat-edit .send-button {
    position: absolute;
    bottom: 30px;
    right: 30px;
    color: #fff;
    background: #3399ff;
    font-size: 16px;
    border: none;
    border-radius: 2px;
    padding: 5px 15px;
    box-shadow: 0 0 10px #3399ff;
    z-index: 11111;
    outline: none;
}
</style>

<style>
.w-e-toolbar {
    background: #fff !important;
    border: none !important;
    border-top: 1px solid #ddd !important;
}

#editor > div:nth-child(2) {
    height: calc(100% - 15px) !important;
    border: none !important;
    overflow: hidden;
}

#editor > div:nth-child(2) > div::-webkit-scrollbar {
    display: none;
}

#editor > div:nth-child(2) > div {
    padding: 0 15px;
}

#editor > div:nth-child(2) > div > p {
    margin: 0;
}

.w-e-panel-tab-content::-webkit-scrollbar {
    /*滚动条整体样式*/
    width: 6px;
    /*高宽分别对应横竖滚动条的尺寸*/
    height: 1px;
}

.w-e-panel-tab-content::-webkit-scrollbar-thumb {
    /*滚动条里面小方块*/
    border-radius: 10px;
    box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.1);
    background: #3d9eff;
}

.w-e-panel-tab-content::-webkit-scrollbar-track {
    /*滚动条里面轨道*/
    box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
    background: #ededed;
}

.w-e-panel-container {
    border: none !important;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.2) !important;
}

.w-e-panel-container {
    height: calc(100% - 30px) !important;
    top: 10px !important;
    width: 315px !important;
}

.w-e-panel-tab-content {
    height: calc(100% - 30px) !important;
}

.w-e-text-container .w-e-panel-container {
    left: 180px !important;
}

.w-e-panel-tab-content > div:nth-child(2),
.w-e-up-img-container {
    top: 50%;
    position: relative;
    transform: translateY(-50%);
}

.magnify-modal {
    z-index: 99999999999 !important;
}

.w-e-panel-tab-content > div:nth-child(2) {
    top: 130px;
}

.w-e-text-container > div img {
    margin: 0 5px;
    width: 25px;
    height: auto;
}

.w-e-emoticon-container img {
    width: 22px;
    height: 22px;
    margin: 2px 0 !important;
}

.w-e-text p {
    line-height: 25px !important;
}
.w-e-text p img {
    width: 25px;
    height: 25px;
    cursor: text;
    line-height: 5px !important;
    vertical-align: middle;
    position: relative;
    top: -2px;
}

.w-e-text p img:hover {
    box-shadow: none;
}

/*图片查看器 开始*/

.magnify-modal {
    box-shadow: 0 0 6px 2px rgba(0, 0, 0, 0.3);
}

.magnify-header .magnify-toolbar {
    background-color: rgba(0, 0, 0, 0.5);
}

.magnify-stage {
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    border-width: 0;
}

.magnify-footer .magnify-toolbar {
    background-color: rgba(0, 0, 0, 0.5);
    border-top-left-radius: 5px;
    border-top-right-radius: 5px;
}

.magnify-header,
.magnify-footer {
    pointer-events: none;
}

.magnify-button {
    pointer-events: auto;
}

/*图片查看器 结束*/
</style>